package com.zqc.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zqc.common.dto.SysMenuDto;
import com.zqc.common.lang.Result;
import com.zqc.entity.SysMenu;
import com.zqc.entity.SysRoleMenu;
import com.zqc.entity.SysUser;
import com.zqc.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zqc
 * @since 2023-03-07
 */
@RestController
@RequestMapping("/sys/menus")
public class SysMenuController extends BaseController {

    @GetMapping("/nav")
    public Result nav(Principal principal) {
        String username = principal.getName();
        // 1.获取用户权限
        SysUser user = sysUserService.getUserByUsername(username);
        String userAuthority = sysUserService.getUserAuthority(user.getId());
        // 将数据转成数组格式
        String[] userAuthorityArray = StringUtils.tokenizeToStringArray(userAuthority, ",");

        // 2.获取侧边导航栏信息
        List<SysMenuDto> nav = sysMenuService.getCurrentUserNav();


        return Result.succ(MapUtil.builder()
                .put("authoritys", userAuthorityArray)
                .put("nav", nav)
                .map()
        );
    }

    // 获取具体菜单的详细信息
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')") // 操作权限控制
    public Result info(@PathVariable(name = "id") Long id) {
        SysMenu menu = sysMenuService.getById(id);
        return Result.succ(menu);
    }

    //查询所有菜单信息
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')") // 操作权限控制
    public Result list() {
        List<SysMenu> treeMenus = sysMenuService.getTreeMenu();
        return Result.succ(treeMenus);
    }

    /**
     * 保存菜单信息
     *
     * @param sysMenu
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result save(@Validated @RequestBody SysMenu sysMenu) {

        sysMenu.setCreated(Timestamp.valueOf(LocalDateTime.now()));

        sysMenuService.save(sysMenu);
        return Result.succ(sysMenu);
    }

    /**
     * 更新菜单信息
     *
     * @param menu
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')") // 操作权限控制
    public Result update(@Validated @RequestBody SysMenu menu) {
        menu.setUpdated(Timestamp.valueOf(LocalDateTime.now()));
        sysMenuService.updateById(menu);
        // 清除所有与该菜单有关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(menu.getId());
        return Result.succ(menu);
    }

    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')") // 操作权限控制
    public Result delete(@PathVariable(name = "id") long id) {
        // 判断该菜单是否有子菜单
        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count > 0) {
            return Result.fail("该菜单有子菜单不能删除");
        }
        // 删除该菜单信息
        sysMenuService.removeById(id);
        // 删除中间关联表中该菜单的信息
        roleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id", id));
        // 删除与该菜单有关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);

        return Result.succ("success");
    }

}
